/* This file wraps ECal class */

%module "evolution"
%{
#include <libecal/e-cal.h>	
%}

struct ECal
{
};



%extend ECal
{
        ECal() {
			GError* err=0;
			ECal* cal= e_cal_new_system_calendar();
			e_cal_open(cal, 0, &err);			
			check_error(err, "Unable to open calendar/task: %s");
			return cal;

		}

        ECal (ESource* src, gboolean force_create=0) {
			GError* err=0;
            ECal* cal= e_cal_new(src, E_CAL_SOURCE_TYPE_EVENT);	
			if(!cal)
			{
				rb_raise(rb_eException, "Unable to create calendar from source", "");
			}
			e_cal_open(cal, force_create, &err);			
			check_error(err, "Unable to open calendar/task: %s");
			return cal;

		}

		ECal* append(ECalComponent* e)	{
			char* uid;
			GError* err=0;
			e_cal_component_commit_sequence(e);
			e_cal_create_object(self, e_cal_component_get_icalcomponent (e), &uid, &err);
			check_error(err, "Unable to create calendar item: %s");
			return self;
		}

		ECal* del(ECalComponent* e){
			const char* uid;
			GError* err=0;
			e_cal_component_commit_sequence(e);
			e_cal_component_get_uid (e, &uid);
			e_cal_remove_object(self, uid, &err);
			check_error(err, "Unable to delete calendar item: %s");
			return self;
		}
		
		ECal* del(const char* uid){
			GError* err=0;
			e_cal_remove_object(self, uid, &err);
			check_error(err, "Unable to delete calendar item: %s");
			return self;
		}
		
		ECalComponent* __getitem__(const char* uid)	{
			GList* l;
			GError* err=0;
			ECalComponent* obj=NULL;			
			char* query = g_strconcat("(uid? \"", uid, "\")", NULL);
			if(e_cal_get_object_list_as_comp (self, query, &l,&err))
			{
				if(l)
					obj = E_CAL_COMPONENT(l->data);	
			}
			g_list_free(l);
			g_free(query);
			return obj;
		}

		int __len__() {
			GList* l;
			GError* err=0;	
			if(e_cal_get_object_list_as_comp (self, "#t", &l,&err)){
				return g_list_length(l);
			}
			return 0;
		}

		
		GList* get_list ()
		{
			GList* l=NULL;;
			GError* err=0;	
			if(e_cal_get_object_list_as_comp (self, "#t", &l,&err))
			{
				return l;
			}			
			return l;
		}
		bool __eq__(ECal* cal)
		{
			ESource *src1=e_cal_get_source(self), *src2=e_cal_get_source(cal);
			return e_source_equal(src1, src2);
		}
		must_free_g_char* __str__() 
		{
			GError* error = 0;
			GList* appts, *l;
			gchar *str, *temp, *result = g_strdup("BEGIN:VCALENDAR\nCALSCALE:GREGORIAN\nPRODID:-//Ximian//NONSGML Evolution Calendar//EN\nVERSION:2.0\n");
			e_cal_get_object_list_as_comp(self, "#t", &appts, &error);			
			for (l = appts; l;l = l->next) {
				 ECalComponent *ev_appt = E_CAL_COMPONENT(l->data);
				 e_cal_component_commit_sequence(ev_appt);
				 str=e_cal_component_get_as_string(ev_appt);
				 temp=g_strconcat(result,str,NULL);
				 g_free(str);
				 g_free(result);
				 result=temp;
				 g_object_unref(ev_appt);
			}
			temp = g_strconcat(result,"END:VCALENDAR\n",NULL);
			g_free(result);
			g_list_free(appts);			
			result=temp;
			return result;
		}
  	 

};

DEFINE_DEFAULT_DESTRUCTOR(ECal)

